package com.computergames.server.protocol;

import com.computergames.server.message.Message;
import com.computergames.server.message.cardMessage.AbstractCardMessage;
import com.computergames.server.message.cardMessage.LandlordMessage;
import com.computergames.server.message.chessMessage.AbstractChessMessage;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

import java.io.IOException;

public class CardMessageDeserializer extends StdDeserializer<AbstractCardMessage> {
    public CardMessageDeserializer() {
        this(null);
    }

    public CardMessageDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public AbstractCardMessage deserialize(JsonParser p, DeserializationContext ctx) throws IOException, JacksonException {
        JsonNode node = p.getCodec().readTree(p);

        // 获取messageType
        int messageType = node.get("messageType").asInt();

        // 根据messageType创建对应的子类实例
        switch (messageType) {
            case Message.LandlordMessage:
                return deserializeLandlord(node);
            // 添加更多case处理其他messageType
            default:
                throw ctx.weirdStringException(node.toString(), AbstractCardMessage.class, "Unknown messageType: " + messageType);
        }
    }

    private LandlordMessage deserializeLandlord(JsonNode node) {
        String[] card = new String[node.get("card").size()];
        for (int i = 0; i < node.get("card").size(); i++) {
            card[i] = node.get("card").get(i).asText();
        }
        return new LandlordMessage(card);
    }
}
